/*
 *  HeartBeatController.cpp
 *  project8
 *
 *  Created by Luca Gobbo on 21-06-10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#include "SpeakerSwitch.h"

          
void SpeakerSwitch::switchOn(int freq, int period){
  if (period > 0){
    nrTicks = 0;
    timeTicks = period;
    maxTicks = (1000 MS) / (2 * freq);   
    state = ON;
    resume();
  }
}                            

void SpeakerSwitch::switchOff(void){
  theSpeaker.low();
  state = OFF;
  suspend();
}


void SpeakerSwitch::init(void){
  switchOff();
}

void SpeakerSwitch::update (void){
  
  switch (state){
    case ON:
      nrTicks = 0;
      theSpeaker.high();     
      state = HIGH;
      break;
    case HIGH:
      nrTicks += getPeriod();      
      if (nrTicks >= maxTicks){
        theSpeaker.low();        
        nrTicks = 0;
        state = LOW;
      }
      break;
      
    case LOW:
      nrTicks+= getPeriod();
       
      if (nrTicks >= maxTicks){
        theSpeaker.high();
       
        nrTicks = 0;
        state = HIGH;
      }
      break;
            
    default:
      mkt_fatal (#UNIQUE_ERROR);
      break;
  }
  timeTicks -= getPeriod();
  if (timeTicks <= 0) switchOff();
  else block();    
}




